package cn.openea.perpartner.space.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.openea.perpartner.space.web.entity.AcceptLog;
import cn.openea.perpartner.space.web.entity.ShareLog;
import cn.openea.perpartner.space.web.mapper.ShareLogMapper;
import cn.openea.perpartner.space.web.service.IAcceptLogService;
import cn.openea.perpartner.space.web.service.IShareLogService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 邀请记录表(ShareLog)表服务实现类
 *
 * @author Weird077
 * @since 2023-03-22 15:19:22
 */
@Service("shareLogService")
public class ShareLogServiceImpl extends ServiceImpl<ShareLogMapper, ShareLog> implements IShareLogService {

    @Autowired
    private IAcceptLogService acceptLogService;
    @Override
    public boolean checkShareIdUnique(String shareId) {
        LambdaQueryWrapper<ShareLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShareLog::getShareId, shareId);
        return count(wrapper)==0;
    }

    @Override
    public ShareLog saveShareLog(ShareLog shareLog) {
        String shareId = RandomUtil.randomString(6);
        if (checkShareIdUnique(shareId)) {
            shareLog.setShareId(shareId);
            save(shareLog);
        } else {
            saveShareLog(shareLog);
        }
        return shareLog;
    }

    @Override
    public String checkShareIdUsed(String userId) {
        LambdaQueryWrapper<ShareLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShareLog::getUserId, userId);
        wrapper.orderByDesc(ShareLog::getCreateTime);
        wrapper.last("limit 1");
        ShareLog shareLog = getOne(wrapper);
        if (BeanUtil.isEmpty(shareLog)) {
            return "";
        }
        LambdaQueryWrapper<AcceptLog> wrap = new LambdaQueryWrapper<>();
        wrap.eq(AcceptLog::getShareId, shareLog.getShareId());
        return acceptLogService.count(wrap)==0?shareLog.getShareId():"";
    }

}

